package com.scs.application.modules.wm.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.mvc.controller.FlowController;
import com.scs.application.core.query.QueryContext;
import com.scs.application.core.query.QueryContextHolder;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.base.entity.ReagentTeam;
import com.scs.application.modules.base.service.ReagentTeamService;
import com.scs.application.modules.dept.entity.Apply;
import com.scs.application.modules.dept.entity.ApplyItem;
import com.scs.application.modules.dept.mapper.ApplyMapper;
import com.scs.application.modules.report.handler.BeforeReport;
import com.scs.application.modules.sys.model.PageResult;
import com.scs.application.modules.sys.model.RestResult;
import com.scs.application.modules.wm.dto.AdjustLocationDTO;
import com.scs.application.modules.wm.entity.*;
import com.scs.application.modules.wm.enums.WorkOrderType;
import com.scs.application.modules.wm.mapper.TransferDemandMapper;
import com.scs.application.modules.wm.service.TransferItemService;
import com.scs.application.modules.wm.service.TransferService;
import com.scs.application.modules.wm.vo.TransferVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/wm/transfer")
public class TransferController extends FlowController<TransferService, Transfer> {
    @Autowired
    ApplyMapper applyMapper;

    @Autowired
    TransferDemandMapper transferDemandMapper;
    @Autowired
    private ReagentTeamService reagentTeamService;
    @Autowired
    private TransferItemService transferItemService;
    /**
     * 根据订单自动转换调拨单
     *
     * @param workOrder
     */
    @PostMapping("/autoChangeTransfer")
    public RestResult autoChangeTransfer(@RequestBody WorkOrder workOrder) {
        Transfer transfer = service.autoChangeTransfer(workOrder);
        return RestResult.ok("转换成功", transfer);
    }

    /**
     * 根据id查询数据
     *
     * @param
     */
    @GetMapping("/findByIdForPDA")
    public RestResult findByIdForPDA(@RequestParam("key") String key, @RequestParam("value") String value) {
        TransferVO distVO = service.findByIdForPDA(key, value);
        return RestResult.ok("查询成功", distVO);
    }

    /**
     * 查询所有非审核通过的调拨单
     *
     * @param busKey
     */
    @GetMapping("/findAllListPDA")
    public RestResult findAllListPDA(@RequestParam("busKey") String busKey) {
        List<Map> allList = service.findAllList(busKey);
        return RestResult.ok("查询成功", allList);
    }



    /**
     * PDA拣货完成
     *
     * @param id
     */
    @PostMapping("/pickFinishedPDA/{id}")
    public RestResult pickFinishedPDA(@PathVariable("id") String id) {
        service.pickFinishedPDA(id);
        return RestResult.ok("操作成功");
    }

    /**
     * 货位调整
     *
     * @param adjustLocationDTO
     * @return
     */
    @PostMapping("/adjustLocation")
    public RestResult adjustLocation(@RequestBody @Valid AdjustLocationDTO adjustLocationDTO) {
        service.adjustLocation(adjustLocationDTO);
        return RestResult.ok("操作成功");
    }

    /**
     * 货位调整
     *
     * @param adjustLocationDTO
     * @return
     */
    @PostMapping("/adjustLocationByType")
    public RestResult adjustLocationByType(@RequestBody @Valid AdjustLocationDTO adjustLocationDTO) {
        return RestResult.ok(service.adjustLocationByType(adjustLocationDTO));
    }


    private void fillEntity(Transfer entity) {
        if (StringUtils.isNotBlank(entity.getReagentTeamId())) {
            ReagentTeam reagentTeam =reagentTeamService.getById(entity.getReagentTeamId());
            if (reagentTeam != null) {
                entity.setReagentTeamName(reagentTeam.getName());
            }
        }
        List<TransferDemand> transferDemandList = transferDemandMapper.selectList(Wrappers.<TransferDemand>query().eq("transfer_id",entity.getId()));
        if (transferDemandList != null && transferDemandList.size() > 0) {
            List<String> refApplyItemIdList = transferDemandList.stream().filter(ob -> StringUtils.isNotBlank(ob.getRefApplyItemId())).map(TransferDemand::getRefApplyItemId).collect(Collectors.toList());
            if (refApplyItemIdList != null && refApplyItemIdList.size() > 0) {
                List<Apply> applyList = applyMapper.getListByApplyItem(Wrappers.<ApplyItem>query().in("id",refApplyItemIdList));
                if (applyList != null && applyList.size() > 0) {
                    List<String> remarkList = applyList.stream().filter(ob -> StringUtils.isNotBlank(ob.getRemark())).map(Apply::getRemark).collect(Collectors.toList());
                    List<String> applyUsers = applyList.stream().filter(ob -> StringUtils.isNotBlank(ob.getBusUser())).map(Apply::getBusUser).collect(Collectors.toList());
                    if (remarkList != null && remarkList.size() > 0) {
                        entity.setDeptAddressName(StringUtils.join(remarkList,","));
                    }

                    if (applyUsers != null && applyUsers.size() > 0) {
                        entity.setApplyUsers(StringUtils.join(applyUsers,","));
                    }
                }
            }
        }

        entity.setCountDtl(transferItemService.count(Wrappers.<TransferItem>query().select("id").eq("transfer_id",entity.getId())));
        entity.setCountDemand(ObjectUtil.length(transferDemandList));
    }

    /**
     * 根据ID查找数据
     */
    @GetMapping("/find")
    public RestResult find(@RequestParam("id") Serializable id) {
        Transfer entity = service.getById(id);
        if (entity == null) {
            return RestResult.error("数据查询失败<br>可能所操作数据已被删除，请刷新后重新尝试操作");
        }
        fillEntity(entity);
        return RestResult.ok("获取数据成功", entity);
    }


    /**
     * 添加/更新数据
     */
    @PostMapping("/save")
    public RestResult saveItem(@Valid @RequestBody Transfer entity) {
        boolean isOk = service.saveOrUpdate(entity);
        if (!isOk) {
            return RestResult.error("数据保存失败");
        }
        fillEntity(entity);
        return RestResult.ok("数据保存成功", entity);
    }

    /**
     *  根据busKey获取调拨单和明细
     * @return
     */
    @GetMapping("/getByBusKey")
    public RestResult getByBusKey(@RequestParam("busKey") String busKey) {
        return RestResult.ok("获取成功", service.getByBusKey(busKey));
    }

    /**
     * 获取数据列表
     */
    @GetMapping("/page")
    public PageResult page() {
        QueryContext queryContext = QueryContextHolder.currentContext();
        if (!BeforeReport.getFlagAllData()) {
            List<String> userWarehouseIdList = BeforeReport.getUserWarehouseIdList();
            QueryWrapper<Transfer> queryWrapper = queryContext.getWrapper();
            String type = queryContext.getParams().get("type")+"";
            switch (type){
                // 科室退货入库
                case WorkOrderType.IN_DEPT_RETURN:{
                    queryWrapper.and(
                            query ->
                                    query.in("to_warehouse_id",userWarehouseIdList)
                    );
                    break;
                }
                // 调拨出库
                case WorkOrderType.OUT_SHIFT:{
                    queryWrapper.and(
                            query ->
                                    query.in("from_warehouse_id",userWarehouseIdList)
                    );
                    break;
                }
                default:{
                    BusinessException.throwValidFail("尚未实现过滤类型:%s",type);
                }
            }
        }
        IPage pageResult = service.page(queryContext);
        return PageResult.ok("查询成功", pageResult.getRecords(), pageResult.getTotal());
    }
}
